package com.qfchen.downloadhelper;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class HttpUrlUtils {

	public static String getStringFromUrl(String url) {
		StringBuffer buffer = new StringBuffer();

		try {
			URL url2 = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) url2
					.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			if (connection.getResponseCode() == 200) {
				InputStream is = connection.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is));
				String string = "";
				while ((string = reader.readLine()) != null) {
					buffer.append(string);
				}
				return buffer.toString();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] getByteFromUrl(String url) {
		InputStream is = null;
		HttpURLConnection connection = null;
		try {
			URL url2 = new URL(url);
			connection = (HttpURLConnection) url2.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			if (connection.getResponseCode() == 200) {
				is = connection.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] bs = new byte[1024];
				int len = 0;
				while ((len = is.read(bs)) != -1) {
					baos.write(bs, 0, len);
					baos.flush();
				}
				return baos.toByteArray();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
					connection.disconnect();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	public static Bitmap getBitmapFromUrl(String url) {
		InputStream is = null;
		HttpURLConnection connection = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Bitmap bitmap = null;
		try {
			URL url2 = new URL(url);
			connection = (HttpURLConnection) url2.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			if (connection.getResponseCode() == 200) {
				is = connection.getInputStream();
				byte[] bs = new byte[1024];
				int len = 0;
				while ((len = is.read(bs)) != -1) {
					baos.write(bs, 0, len);
					baos.flush();
				}
				byte[] result = baos.toByteArray();
				bitmap = BitmapFactory
						.decodeByteArray(result, 0, result.length);
				return bitmap;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
